from flask import Flask, jsonify
from flask import request, render_template
import sys, os, subprocess
import datetime

app = Flask(__name__, template_folder='./templates', static_folder='./web')

SN = ""


@app.route('/')
def hello_world():
    return render_template('index.html')


@app.route('/api/kill', methods=['GET'])
def kill():
    res = ""
    try:
        cmd = "pkill java"
        res = subprocess.check_output(cmd, shell=True).decode('utf-8')
    except Exception as e:
        pass
    data = {'code': 0}
    return jsonify(data)


@app.route('/api/output', methods=['GET'])
def out():
    s = request.args
    if 'jobname' in s:
        jobname = request.args.get('jobname')
    else:
        jobname = 'init.jmx'
    res = subprocess.check_output('ps aux | grep {jobname} | wc -l'.format(jobname=jobname), shell=True).decode('utf-8')
    res = int(res[:-1])
    # print(jobname, ":->", res)
    content = ""
    code = 0  # 0:正在运行；1运行成功
    if res == 2:  # 运行成功或出错
        jtlPath = "/root/web/{job}/{job}.jtl".format(job=jobname.split('.')[0])
        with open(jtlPath) as f:
            content = f.read()
        code = 1
    else:
        content = "正在运行"
    return jsonify({'content': content, 'code': code})


now = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")


@app.route('/api/html', methods=['GET'])
def htmlGen():
    # return jsonify({'api': 'del data'})
    s = request.args
    if 'jobname' in s:
        jobname = request.args.get('jobname')
    else:
        jobname = 'init.jmx'

    preName = jobname.split('.')[0]
    # t = subprocess.check_output('ls /root/web/init -u | grep .jtl | head -1', shell=True).decode('utf-8')
    tempFile = subprocess.check_output(
        'ls /root/web/{preName} -u | grep .jtl | head -1'.format(preName=preName,
                                                                 jobname=jobname,
                                                                 now=now),
        shell=True).decode('utf-8')[:-1]

    res = subprocess.check_output(
        'jmeter -g /root/web/{preName}/{tempFile}.jtl -o /root/web/{preName}/report_{tempFile}'.format(preName=preName,
                                                                                                   tempFile=
                                                                                                   tempFile.split('.')[
                                                                                                       0]),
        shell=True).decode('utf-8')
    # res = int(res[:-1])
    url = "http://jmeterreport.k8s.tbocii.tk:8000/root/web/{preName}/report_{tempFile}/".format(preName=preName,
                                                                                               tempFile=
                                                                                               tempFile.split('.')[0])
    return jsonify({'url': url, 'code': 0})


scriptPath = '/root/scripts'  # 脚本目录


@app.route('/api/upload', methods=['POST'])
def fileSave():
    storeplace = scriptPath
    isExtist = os.path.exists(storeplace)
    data = ""
    if not isExtist:  # 如果目录不存在，则新建
        os.makedirs(storeplace)
    upfile = request.files['file']  # file关键字
    upfile.save(storeplace + '/%s' % upfile.filename)

    # print(upfile.filename, "已存储")
    data = {
        "state": "SUCCESS",
        "url": scriptPath + "/%s" % upfile.filename,
        "name": upfile.filename,
        "original": upfile.filename
    }
    SN = upfile.filename
    u = runJmeter(upfile.filename)
    data['output'] = u

    return jsonify(data)


def runJmeter(fileName):
    fqz = fileName.split('.')[0]
    storeplace = '/root/web/' + fqz  # 判断报告目录是否存在

    isExtist = os.path.exists(storeplace)
    res = ""
    now = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
    try:

        if isExtist:
            cmd = 'jmeter -n -t {fileName} -l /root/web/{fqz}/{fqz}_{now}.jtl'.format(
                fileName=scriptPath + '/' + fileName,
                fqz=fqz,
                now=now)

        else:
            cmd = 'jmeter -n -t {fileName} -l /root/web/{fqz}/{fqz}_{now}.jtl'.format(
                fileName=scriptPath + '/' + fileName,
                fqz=fqz, now=now)
        # print('running->', cmd)
        res = subprocess.check_output(cmd, shell=True).decode('utf-8')
    except Exception as e:
        pass
    return res


if __name__ == "__main__":
    app.run(port=8000, host='0.0.0.0', debug=True)
